package com.jjwxc.jwjskandriod.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.AllStackViewHolder;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.FFUtils;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.AllStackRequest;
import com.jjwxc.jwjskandriod.model.ChannelListResponse;
import com.jjwxc.jwjskandriod.model.FindRequest;
import com.jjwxc.jwjskandriod.model.FindResponse;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.jjwxc.jwjskandriod.widget.OptionalPop;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class FindContentActivity extends BaseActivity {


    private RecyclerView rv_find;

    private RadioGroup tabLayout;

    private final String[] TAB_TITLES = new String[]{"搜作品", "搜作者", "搜类型"};

    TabLayout tabLayoutOne;
    TabLayout tabLayoutTwo;
    TabLayout tabLayoutThree;
    LinearLayout ll_option;

    private FindContentAdapter adapter;
    private String channels = "";
    private String word = "";
    private String sortType = "1";
    private String keyWord;
    private int type = 1;
    AllStackRequest allStackRequest = new AllStackRequest();
    List<ChannelListResponse.DataBean> mData = new ArrayList<>();
    private boolean isRefresh = true;
    private TextView tv_jieguo;
    private TextView tv_tuijian;
    private EditText editText;
    private ImageView img_find;

    @Override
    public int getContentViewId() {
        return R.layout.activity_findcontent;
    }

    @Override
    public void findView() {
        tabLayout = findViewById(R.id.tab_find_layout);
        rv_find = findViewById(R.id.rv_find);
        tabLayoutOne = findViewById(R.id.tab_find_one);
        tabLayoutTwo = findViewById(R.id.tab_find_two);
        tabLayoutThree = findViewById(R.id.tab_find_three);
        tv_jieguo = findViewById(R.id.tv_jieguo);
        tv_tuijian = findViewById(R.id.tv_tuijian);
        editText = findViewById(R.id.ed_comment);
        img_find = findViewById(R.id.img_find);
        ll_option = findViewById(R.id.ll_option);
    }

    @Override
    public void setListener() {
        setNoTitle();
        keyWord = getIntent().getStringExtra("content");
        editText.setText(keyWord);

        editText.setOnKeyListener((view, keyCode, event) -> {
                    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                        //先隱藏鍵盤
                        ((InputMethodManager) FindContentActivity.this.getSystemService(INPUT_METHOD_SERVICE))
                                .hideSoftInputFromWindow(FindContentActivity.this.getCurrentFocus()
                                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                        keyWord = editText.getText().toString();

                        getsearch();
                    }
                    return false;
                }
        );

        img_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyWord = editText.getText().toString();

                getsearch();
            }
        });
        ll_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new OptionalPop().optionalPopWindow(v, FindContentActivity.this, allStackRequest, new OptionalPop.PopOptionalListener() {
                    @Override
                    public void onValueClick(AllStackRequest value) {
                        isRefresh = false;
                        allStackRequest = value;
                        if (value.getChannels() != null && value.getChannels().size() > 0) {
                            channels = value.getChannels().get(0);
                        } else {
                            channels = "";
                        }
                        if (!StUtils.isEmpty(value.getWordSize())) {
                            word = value.getWordSize();
                        } else {
                            word = "";
                        }
                        if (!StUtils.isEmpty(value.getSortType())) {
                            sortType = value.getSortType();
                        } else {
                            sortType = "1";
                        }
                        String s = value.getWordSize();
                        if (StUtils.isEmpty(s)) {
                            tabLayoutTwo.getTabAt(0).select();
                        } else {
                            tabLayoutTwo.getTabAt(Integer.parseInt(s)).select();
                        }
                        String rs = value.getReadingStatus();
                        if (StUtils.isEmpty(rs)) {
                            tabLayoutThree.getTabAt(0).select();
                        } else {
                            tabLayoutThree.getTabAt(Integer.parseInt(rs)).select();
                        }
                        int selectOne = 0;
                        if (value.getChannels().size() > 0) {
                            for (int i = 0; i < mData.size(); i++) {
                                if (mData.get(i).getChannelId().equals(value.getChannels().get(0))) {
                                    selectOne = i;
                                }
                            }
                        }
                        tabLayoutOne.getTabAt(selectOne).select();
                        if (!isRefresh) {
                            getsearch();
                            isRefresh = true;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void afterCreate() {
        setTabs(tabLayout, getLayoutInflater(), TAB_TITLES);
        rv_find.setNestedScrollingEnabled(false);
        rv_find.setFocusable(false);
        rv_find.setLayoutManager(new LinearLayoutManager(FindContentActivity.this));
        rv_find.addItemDecoration(new LinearLayouDecoration(FindContentActivity.this,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        rv_find.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new FindContentAdapter(this);
        rv_find.setAdapter(adapter);
        String[] TAB_TITLES = new String[]{"默认", "30万以下", "30-50万", "50-100万", "100万以上"};
        setTwoTabs(tabLayoutTwo, getLayoutInflater(), TAB_TITLES, 2);
        String[] TAB = new String[]{"累计热度", "销售量", "完结时间"};
        setTwoTabs(tabLayoutThree, getLayoutInflater(), TAB, 3);
        setTabOne();
        getsearch();
    }


    public void getsearch() {
        allStackRequest.setFindString(editText.getText().toString());

        List<String> list = PreUtils.getList("find_log");
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() >= 9) {
            list.remove(0);
        }
        String string = list.toString();
        if (!string.contains(keyWord)) {
            list.add(keyWord);
            PreUtils.setListString("find_log", list);
        }
        FindRequest findRequest = new FindRequest();
        findRequest.setKeyword(keyWord);
        findRequest.setSearchType(type + "");
        if (type == 3) {
            if (!StUtils.isEmpty(channels)) {
                List<String> channerl = new ArrayList<>();
                channerl.add(channels);
                allStackRequest.setChannels(channerl);
            } else {
                allStackRequest.setChannels(null);
            }
            allStackRequest.setLimit(10);
            allStackRequest.setOffset(10);
            allStackRequest.setWordSize(word);
            allStackRequest.setSortType(sortType);
            findRequest.setAllStackRequest(allStackRequest);
        }

        post(Url.search, "搜索中", FindResponse.class, new FFNetWorkCallBack<FindResponse>() {
            @Override
            public void onSuccess(FindResponse response) {
                if (response.getCode() == 200) {
                    List<FindResponse.DataBean> bookList = response.getData().getBooks();
                    List<FindResponse.DataBean> recommentList = response.getData().getRecommendBooks();

                    if (bookList.size() == 0 && recommentList.size() > 0) {
                        adapter.setData(recommentList);
                        tv_tuijian.setText("大家都在看");
                        tv_tuijian.setVisibility(View.VISIBLE);
                        tv_jieguo.setVisibility(View.VISIBLE);
                        if (type == 3) {
                            tabLayoutOne.setVisibility(View.VISIBLE);
                            tabLayoutTwo.setVisibility(View.VISIBLE);
                            tabLayoutThree.setVisibility(View.VISIBLE);
                            ll_option.setVisibility(View.VISIBLE);
                        } else {
                            tabLayoutOne.setVisibility(View.GONE);
                            tabLayoutTwo.setVisibility(View.GONE);
                            tabLayoutThree.setVisibility(View.GONE);
                            ll_option.setVisibility(View.GONE);
                        }
                        switch (type) {
                            case 1:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_WORK_NO_RESULT);
                                break;
                            case 2:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_AUTHOR_NO_RESULT);
                                break;
                            case 3:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_TYPE_NO_RESULT);
                                break;
                        }
                    } else if (bookList.size() > 0 && recommentList.size() == 0) {
                        tv_jieguo.setVisibility(View.GONE);
                        adapter.setData(bookList);
                        if (type == 2) {
                            tv_tuijian.setVisibility(View.VISIBLE);
                            tv_tuijian.setText("全部作品");
                        } else {
                            tv_tuijian.setVisibility(View.GONE);

                        }
                        if (type == 3) {
                            tabLayoutOne.setVisibility(View.VISIBLE);
                            tabLayoutTwo.setVisibility(View.VISIBLE);
                            tabLayoutThree.setVisibility(View.VISIBLE);
                            ll_option.setVisibility(View.VISIBLE);
                        } else {
                            tabLayoutOne.setVisibility(View.GONE);
                            tabLayoutTwo.setVisibility(View.GONE);
                            tabLayoutThree.setVisibility(View.GONE);
                            ll_option.setVisibility(View.GONE);
                        }
                        switch (type) {
                            case 1:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_WORK_RESULT);
                                break;
                            case 2:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_AUTHOR_RESULT);
                                break;
                            case 3:
                                MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_TYPE_RESULT);
                                break;
                        }
                    }

                }


            }

            @Override
            public boolean onFail(FindResponse response) {
                return false;
            }
        }, JSON.toJSONString(findRequest));

    }

    public void setTabOne() {
        post(Url.listChannel, null, ChannelListResponse.class, new FFNetWorkCallBack<ChannelListResponse>() {
            @Override
            public void onSuccess(ChannelListResponse response) {
                if (response.getCode() == 200 && response.getData().size() > 0) {
                    mData.clear();
                    ChannelListResponse.DataBean bean = new ChannelListResponse.DataBean();
                    bean.setName("默认");
                    bean.setChannelId("");
                    mData.add(bean);
                    mData.addAll(response.getData());
                    setOneTabs(tabLayoutOne, getLayoutInflater(), mData);
                }
            }

            @Override
            public boolean onFail(ChannelListResponse response) {
                return false;
            }
        }, "{}");
    }

    /**
     * 设置页卡显示1
     *
     * @param tabLayout
     * @param inflater
     */
    private void setOneTabs(TabLayout tabLayout, LayoutInflater inflater, List<ChannelListResponse.DataBean> list) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list.get(i).getName());
            tabLayout.addTab(tab);

            // 默认选中类型
            if (!TextUtils.isEmpty(editText.getText().toString()) && list.get(i).getName().equals(editText.getText().toString())) {
                tab.select();
            }
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                if (tab.getPosition() == 0) {
                    channels = "";
                } else {
                    channels = list.get(tab.getPosition()).getChannelId();
                }
                getsearch();
            }}

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //最后再给刷新的权限
        isRefresh = true;
    }

    /**
     * 设置页卡显示效果2
     */
    private void setTwoTabs(TabLayout tabLayout, LayoutInflater inflater, String[] list, int page) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list[i]);
            tabLayout.addTab(tab);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                    if (page == 2) {
                        if (tab.getPosition() == 0) {
                            word = "";
                        } else {
                            word = tab.getPosition() + "";
                        }
                    } else {
                        sortType = (tab.getPosition() + 1) + "";
                    }
                    getsearch();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }


    private void setTabs(RadioGroup tabLayout, LayoutInflater inflater, String[] tabTitlees) {
        tabLayout.removeAllViews();
        for (int i = 1; i <= tabTitlees.length; i++) {
            RadioButton view = (RadioButton) inflater.inflate(R.layout.find_item_content, null);
            view.setId(i);
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FFUtils.getPx(30));
            layoutParams.setMargins(15, 0, 0, 0);
            view.setLayoutParams(layoutParams);
            if (i == 1) {
                view.setChecked(true);
            } else {
                view.setChecked(false);
            }
            view.setText(tabTitlees[i - 1]);
            tabLayout.addView(view);
            int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    type = finalI;
                    getsearch();
                    switch (type) {
                        case 1:
                            MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_WORK_CLICK);
                            break;
                        case 2:
                            MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_AUTHOR_CLICK);
                            break;
                        case 3:
                            MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_TYPE_CLICK);
                            break;
                    }
                }
            });

        }


    }

    public class FindContentAdapter extends BaseRecyclerAdapter<AllStackViewHolder> {
        private Context context;


        private List<FindResponse.DataBean> mData = new ArrayList<>();


        public FindContentAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<FindResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<FindResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public AllStackViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.allstack_item_list, parent, false);
            AllStackViewHolder viewHolder_text = new AllStackViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public AllStackViewHolder getViewHolder(View view) {
            return new AllStackViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(final AllStackViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            FFImageLoader.loadImage(context, holder.img_allstack_item, mData.get(position).getCoverImgUrl() + "", mData.get(position).getBookId(), true);

            if (mData.get(position).getName().contains(keyWord)) {
                String[] strarray = mData.get(position).getName().split(keyWord);
                Spanned spanned;
                if (strarray.length > 1) {
                    spanned = Html.fromHtml(strarray[0] + "<font color= #F25C5B>" + keyWord + "</font>" + strarray[1]);
                    holder.tv_bookname_allstack.setText(spanned);
                } else if (strarray.length != 0) {
                    spanned = Html.fromHtml(strarray[0] + "<font color= #F25C5B>" + keyWord + "</font>");
                    holder.tv_bookname_allstack.setText(spanned);
                } else {
                    holder.tv_bookname_allstack.setText(mData.get(position).getName());
                }

            } else {
                holder.tv_bookname_allstack.setText(mData.get(position).getName());
            }

            holder.tv_book_author.setText(mData.get(position).getAuthor());
            holder.tv_book_info.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_allstack_tab.setText(mData.get(position).getChannlname());
            holder.cl_allstack_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(FindContentActivity.this, BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                    MobclickAgent.onEvent(FindContentActivity.this, UMConstant.POPULAR_SEARCH_RESULT_CLICK);
                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }
}
